import fetch from 'dva/fetch';
import React, { Component } from 'react';
import { Layout, Tabs, Form, Modal, Spin, message } from 'antd';
import styles from '../../../index.less';
import Toolbar from '../../Common/ToolBar/ToolBar';
import TabMainTable from './TabMainTable';
import TabSubjectContent from './TabSubjectContent';
import TabExamine from './TabExamine';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';
import baseHigher from '../../Common/baseHigher';
import PpopupPan from '../../../routes/ppopupPan/ppopupPan';


const { confirm } = Modal;
const { Header, Content } = Layout;
const { TabPane } = Tabs;

class SendCar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: config.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, /* 主表 + 从表 配置 */
      sId: '', /* 业务数据ID */
      mainTable: '', /* 主表 */
      sActiveId: '', /* 窗体Id */
      tabSubjectContent: '', /* 主体内容 */
      tabExamine: '', /* 审核信息 */
      disabled: false, /* 是否是查看状态 */
      saleSlaveData: [],
      salesOrderData: [],
      salesResultData: [],
      loading: false,
      modalVisible: false, /* 弹窗显示状态 */
      modalPanel: {}, /* 弹窗面板属性 */
      listRecordKey: { salesOrderDataKey: '', saleSlaveDataKey: '', salesResultDataKey: '' }, /* 列表弹窗当前操作行,内部属性根据模块不同自定义 */
    };
  }
  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    /* 配置 */
    const {
      sDataListTabId, urlData, formRoute, loading, sId,
    } = dataList;
    /* 数据Id */
    const { formId } = nextProps;
    /* 窗体全部配置 */
    const masterConfig = commonFunc.getWindowConfig('salsendcarmaster', nextProps.formData);
    /* 弹出窗数据返回,渲染数据并关闭弹出框 */
    if ((nextProps.app.ppopupPane !== undefined &&
      nextProps.app.ppopupPane.mainConfig !== undefined) ? (nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key
      && nextProps.formRoute === nextProps.app.ppopupPane.mainConfig.route) : false) {
      const { resultValue } = nextProps.app.ppopupPane;
      const { modalType } = nextProps.app.ppopupPane;
      /* 通用弹窗数据返值处理 */
      if ((resultValue !== undefined ? resultValue !== undefined : false) && modalType === 'ppopup') {
        /* 数据集名 */
        const { dataName } = nextProps.app.ppopupPane;
        /* 数据集类型，对象型为Map 数组型为List */
        const { dataType } = nextProps.app.ppopupPane;
        const data = this.state[`${dataName}`];
        const { mainKey } = nextProps.app.ppopupPane;
        if (dataType === 'Map') {
          data[`${mainKey}`] = resultValue;
          this.setState({ [`${dataName}`]: data, modalVisible: false });
        } else if (dataType === 'List') {
          data.map((item) => {
            if ((item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey[`${dataName}Key`]) {
              item[`${mainKey}`] = resultValue;
            }
            return item;
          });
          /* 弹窗数据回填后，清空listRecordKey 避免数据污染 */
          this.setState({ [`${dataName}`]: data, modalVisible: false, listRecordKey: { salesOrderDataKey: '', saleSlaveDataKey: '', salesResultDataKey: '' } });
        }
        /* 弹出框关闭 */
        this.props.onRemoveModalPane({});
        return;
      }
    }
    if (nextProps.sTabId === sDataListTabId && nextProps.formRoute === formRoute && nextProps.formData.length > 0) {
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      if (dataList.returnType !== undefined && dataList.returnType === 'CUD') {
        if (sId !== undefined && sId !== '') {
          this.setState({ sId });
        }
        this.setState({ disabled: dataList.disabled });
        this.handleRefresh(sId);
        return;
      }
      /* 窗体显示配置 */
      const masterShowConfig = commonFunc.getConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
      if (this.state.sActiveId === '') {
        const supplyPan = nextProps.app.currentPane;
        /* 获取工具栏, 主表，页签标题 */
        this.setState({ toolProps: nextProps });
        const { formData } = urlData;
        /* 窗体配置 */
        const mainTable = formData.filter(item => (item.sTbName.toLowerCase() === 'salsendcarmaster'))[0];
        /* 匹配主表 */
        const mainConfig = mainTable.gdsconfigformslave;
        const tabSubjectContent = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabsubjectcontent'))[0];
        const tabExamine = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabexamine'))[0];
        /* 从表配置 */
        this.setState({
          formData,
          mainTable,
          disabled: supplyPan.disabled !== undefined ? supplyPan.disabled : false,
          sId: supplyPan.checkedId !== undefined ? supplyPan.checkedId : '',
          sActiveId: formId,
          mainConfig,
          tabSubjectContent: tabSubjectContent !== undefined ? tabSubjectContent : { showName: '主体内容', sId: new Date().getTime() + 1 }, /* 页签名 */
          tabExamine: tabExamine !== undefined ? tabExamine : { showName: '审核信息', sId: new Date().getTime() + 2 },
        });
        this.setState({ masterConfig, masterShowConfig });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data' && dataList.componentName.indexOf('salsendcarmaster') <= 0) {
        const salesOrderData = Object.keys(urlData).length > 0
          ? urlData[0] : [];
        this.setState({ salesOrderData, loading: false });
      }
    }
    if (dataList.returnType !== undefined && dataList.returnType === 'data' && dataList.componentName === 'salsendcarslave') {
      const saleSlaveData = Object.keys(urlData).length > 0
        ? urlData : [];
      this.setState({ saleSlaveData, loading: false });
    }
    if (dataList.returnType !== undefined && dataList.returnType === 'data' && dataList.componentName === 'sysbillcheckresult') {
      const salesReslutData = Object.keys(urlData).length > 0
        ? urlData : [];
      this.setState({ salesReslutData, loading: false });
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    let flag = true;
    /* 追加弹出框数值回填放行判断ppopupPane */
    if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined &&
      nextProps.app.ppopupPane.mainConfig !== undefined) ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
      if (nextState.disabled !== this.state.disabled) {
        return true;
      }
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  /* 刷新 */
  handleRefresh = (newsId) => {
    const { dispatch } = this.props;
    const {
      masterConfig, sId, sActiveId, formData,
    } = this.state;
    let id = sId;
    if (newsId !== undefined && newsId !== '') {
      id = newsId;
    }
    if (id !== undefined && id !== '') {
      /* 表Id */
      const mainId = masterConfig.sId;
      /* 业务数据Id */
      const value = { sId: id };
      const sTabId = this.props.app.currentPane.key;
      /* 从表value */
      const slaveValue = {
        sSqlCondition: {
          sParentId: id,
        },
      };
      const salesOrderSlaveConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'salsendcarslave'))[0];
      const salesReslutConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'sysbillcheckresult'))[0];
      const salesOrderSlaveId = salesOrderSlaveConfig.sId;
      const salseResultId = salesReslutConfig.sId;
      const mainDataUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${mainId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mainDataUrl, sTabId, componentName: 'salsendcarmaster', value, formRoute: '/salsendcarmaster', returnType: 'data',
        },
      });
      const salesOrderSlaveDataUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${salesOrderSlaveId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: salesOrderSlaveDataUrl, sTabId, componentName: 'salsendcarslave', value: slaveValue, formRoute: '/salsendcarslave', returnType: 'data',
        },
      });
      const salesResultDataUrl = `${config.server_host}business/getBusinessDataByFormcustomId/${salseResultId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: salesResultDataUrl, sTabId, componentName: 'sysbillcheckresult', value: slaveValue, formRoute: '/sysbillcheckresult', returnType: 'data',
        },
      });
    } else {
      /* 应清空所有组件,或刷新不做任何处理或屏蔽刷新按钮 */
    }
  };
  /* 新增 */
  handleAdd= () => {
    /* Tab标签Id */
    this.setState({
      salesOrderData: [], saleSlaveData: [], salesReslutData: [], disabled: false, sId: '',
    });
  };
  /* 修改 */
  handleEdit = (obj) => {
    const { disabled } = obj;
    this.setState({ disabled });
  };
  /* 删除 */
  handleDel = () => {
    const onhandleOk = this.handleOk;
    const { sId, sActiveId } = this.state;
    const { token } = this.props.app;
    confirm({
      title: '确定要删除?',
      onOk() {
        const value = {
          data: {
            sMasterTable: 'salsendcarmaster',
            sId: [sId],
            sSlaveTable: [
              { tableName: 'salsendcarslave', relationName: 'sParentId' },
              { tableName: 'sysbillcheckresult', relationName: 'sParentId' }],
          },
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}business/delMasSlaBusinessData?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onhandleOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  }
  /* 取消 */
  handleCancel =(type) => {
    const onhandleOk = this.handleOk;
    confirm({
      title: '确定要取消?',
      onOk() {
        onhandleOk(type);
      },
      onCancel() {},
    });
  };
  /* 数据自动变更 */
  handleFormChange = (value) => {
    const { supplyData } = this.state;
    this.setState({
      supplyData: { ...supplyData, ...value },
    });
  };
  /* 确认取消 */
  handleOk = () => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === this.props.app.currentPane.key) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== this.props.app.currentPane.key);
    let currentPane;
    if (lastIndex >= 0) {
      currentPane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      currentPane = panes[lastIndex + 1];
    } else {
      currentPane = { title: '', route: '', key: '0' };
    }
    this.props.onRemovePane(panes, currentPane);
  };
  /* 保存 */
  handleSubmit() {
    const { dispatch } = this.props;
    /* 业务数据Id */
    const sTabId = this.props.app.currentPane.key;
    this.form.validateFields((err) => {
      if (!err) {
        const inputValue = this.state.supplyData;
        const { sActiveId } = this.state;
        const dataUrl = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
        if (this.state.sId !== '') {
          inputValue.handleType = 'update';
          const value = {
            data: [{
              sTable: 'salsendcarmaster',
              column: [inputValue],
            }, {
              sTable: 'salsendcarslave',
              column: this.state.contactsData,
            }],
            sClientType: '1',
          };
          dispatch({
            type: 'content/getUrlPostData',
            payload: {
              url: dataUrl, sTabId, value, componentName: 'salsendcarmaster', formRoute: '/salsendcarmaster', returnType: 'CUD',
            },
          });
        } else {
          inputValue.handleType = 'add';
          const options = {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
          };
          const url = `${config.server_host}getUuid`;
          fetch(url, options).then(response => response.json()).then((json) => {
            if (json.code === 1) {
              const sId = json.dataset.rows[0];
              inputValue.sId = sId;
              /* 把新增时获取的唯一主键放在STATE中用于成功后刷新动作 */
              inputValue.maxBillNo = 'sSupplyNo';
              const { saleSlaveData, salesReslutData } = this.state;
              for (const item of saleSlaveData) {
                item.sParentId = sId;
              }
              for (const item of salesReslutData) {
                item.sParentId = sId;
              }
              const value = {
                data: [{
                  sTable: 'salsendcarmaster',
                  column: [inputValue],
                }, {
                  sTable: 'salsendcarslave',
                  column: saleSlaveData,
                }, {
                  sTable: 'sysbillcheckresult',
                  column: salesReslutData,
                }],
                sClientType: '1',
              };
              dispatch({
                type: 'content/getUrlPostData',
                payload: {
                  url: dataUrl, sTabId, value, componentName: 'salsendcarmaster', formRoute: '/salsendcarmaster', returnType: 'CUD', sId,
                },
              });
            }
          });
        }
      }
    });
  }

  handleContactsData = (value) => {
    const contactsDataState = [...this.state.contactsData];
    const contactsDataDel = contactsDataState.filter(item => (item.handleType === 'del'));
    const contactsData = [...contactsDataDel, ...value];
    for (const item of contactsData) {
      item.sParentId = this.state.sId;
    }
    this.setState({
      contactsData,
    });
  };

  handleAddressData = (value) => {
    const addressDataState = [...this.state.addressData];
    const addressDataDel = addressDataState.filter(item => (item.handleType === 'del'));
    const addressData = [...addressDataDel, ...value];
    for (const item of addressData) {
      item.sParentId = this.state.sId;
    }
    this.setState({
      addressData,
    });
  };

  handleForm = (form) => {
    this.form = form;
  };

  /* 弹窗关闭 */
  handlePpopUpPaneCancel = () => {
    /* 弹窗类型，下拉/弹窗 */
    const { modalType } = this.props.app.ppopupPane;
    /* 数据集名 */
    const { dataName } = this.props.app.ppopupPane;
    const data = this.state[`${dataName}`];
    /* 如果为下拉新增则下拉值重置为空 */
    if (modalType === 'select') {
      /* 数据集类型，对象型为Map 数组型为List */
      const { dataType } = this.props.app.ppopupPane;
      const { mainKey } = this.props.app.ppopupPane;
      /* 窗体关闭时下拉重置为空,避免下拉项停留在NEW选项 */
      if (dataType === 'Map' && data[`${mainKey}`] === '000') {
        data[`${mainKey}`] = ' ';
      } else if (dataType === 'List') {
        data.map((item) => {
          if (item.key === this.state.listRecordKey[`${dataName}Key`] && item[`${mainKey}`] === '000') {
            item[`${mainKey}`] = ' ';
          }
          return item;
        });
      }
    }
    /* 置空models中弹窗面板 */
    this.props.onRemoveModalPane({});
    /* 隐藏弹窗面板 */
    this.setState({ modalVisible: false, [`${dataName}`]: data, listRecordKey: { salesOrderDataKey: '', salesReslutDataKey: '' } });
  };

  /* 弹窗面板状态更改 */
  handleModalPane = (value) => {
    this.setState({ modalVisible: value.modalVisible });
  }

  /* 用于返回列表编辑框弹窗所属行主键 */
  handleRecordKey = (value) => {
    const { listRecordKey } = this.state;
    this.setState({ listRecordKey: { ...listRecordKey, ...value } });
  }

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    const { loading } = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          {pageLoading ? '' :
          <div>
            <SendCarComponent
              {...props}
              {...state}
              handleSubmit={this.handleSubmit.bind(this)}
              handleEdit={this.handleEdit.bind(this)}
              handleAdd={this.handleAdd.bind(this)}
              handleOk={this.handleOk.bind(this)}
              handleCancel={this.handleCancel.bind(this)}
              handleRefresh={this.handleRefresh.bind(this)}
              handleDel={this.handleDel.bind(this)}
              onChange={this.handleFormChange.bind(this)}
              handleForm={this.handleForm.bind(this)}
              handleContactsData={this.handleContactsData.bind(this)}
              handleAddressData={this.handleAddressData.bind(this)}
              handleModalPane={this.handleModalPane.bind(this)}
              handleRecordKey={this.handleRecordKey.bind(this)}
              onModalClose={this.handlePpopUpPaneCancel}
            />
            <Modal
              title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
              visible={this.state.modalVisible}
              onCancel={this.handlePpopUpPaneCancel.bind(this)}
              footer={null}
              width={1000}
            >
              <PpopupPan handleGetResult={this.handleGetResult} />
            </Modal>
          </div>}
        </Spin>
      </div>
    );
  }
}

const SendCarComponent = Form.create({
  // mapPropsToFields(props) {
  // const { salesOrderData, masterShowConfig } = props;
  // const obj = commonFunc.mapPropsToFieldsChangeValue(masterShowConfig, salesOrderData);
  //   return obj;
  // },
  // onValuesChange(props, values) {
  //   props.onChange(values);
  // },
  // onFieldsChange(props, changedFields) {
  //   console.log('onFieldsChange...', changedFields);
  // },
})((props) => {
  const { app, form } = props;
  const {
    sActiveId,
    masterConfig,
    sId,
    formData,
    dispatch,
    disabled,
    changeDataFlag, content,
  } = props;
  /* 主表 */
  const { handleForm, onModalClose } = props;
  const onClose = onModalClose;
  const childProps = {
    app, form, sActiveId, sId, disabled, dispatch, content, masterConfig, onClose,
  };
  const mainProps = {
    formData, componentName: 'salsendcarmaster', ...childProps, changeDataFlag,
  };
  /* 页签 */
  const { tabSubjectContent, tabExamine } = props;
  const subjectProps = {
    formData, componentName: 'salsendcarslave', ...childProps, changeDataFlag,
  };
  const examineProps = {
    formData, componentName: 'sysbillcheckresult', ...childProps, changeDataFlag,
  };
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar componentName="toolsalesorder" {...props}>
            {handleForm(form)}
          </Toolbar>
        </Header>
        <Layout className={styles.clayout}>
          <Content className={styles.content}>
            <TabMainTable {...mainProps} />
            <Tabs defaultActiveKey="2" size="small" style={{ paddingBottom: 20 }}>
              <TabPane tab={tabSubjectContent.showName} key={2} >
                <TabSubjectContent {...subjectProps} />
              </TabPane>
              <TabPane tab={tabExamine.showName} key={3} >
                <TabExamine {...examineProps} />
              </TabPane>
            </Tabs>
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});


export default baseHigher(SendCar);
